//
//  OAuthViewController.swift
//  LVWeibo
//
//  Created by lv on 15/6/26.
//  Copyright © 2015年 lv. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController,UIWebViewDelegate {
    
    // 定义常量
    private let WB_Client_ID     = "4158492090"
    private let WB_Redirect_URI  = "http://baidu.com"
    private let WB_Client_Secret = "be6415007618ae95c957c6e78c33e537"
    private let WB_Grant_Type    = "authorization_code"
    private let WB_Token_UrlStr  = "oauth2/access_token" // 相对路径

    // 定义webView的变量属性
    var webView:UIWebView?
    
    // 让控制器的View为webView
    override func loadView() {
        webView = lwebView
        // 设置webView的代理
        webView?.delegate = self
        view = webView
        title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // 加载授权页面
        loadAuthPage()
    }
    
    ///  加载授权页面
    private func loadAuthPage() {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_Client_ID)&redirect_uri=\(WB_Redirect_URI)"
        let url = NSURL(string: urlString)!
        let request = NSURLRequest(URL: url)
        webView!.loadRequest(request)
    }
    
    //MARK:- 实现代理方法
    // 1> 如果是新浪的 URL，就继续加载
    // 2> 如果是回调地址，需要根据 URL 中的内容，判断是否有授权码
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // 1.完成路径
        let urlString = request.URL!.absoluteString
        print(urlString)
        // 2.若不是授权回调地址 继续加载
        if !urlString.hasPrefix(WB_Redirect_URI) {
            return true
        }
        
        // 3.是回调地址，判断是否有授权码并取出
        // 获取url字符串中的query
        let queryString = request.URL!.query!
        let codeStr = "code="
        // 判断是否包含codeStr
        if queryString.hasPrefix(codeStr) {
            // 包含
            let code = queryString.substringFromIndex(advance(codeStr.endIndex, 0))
            print("授权码：\(code)")
            
            // 使用授权码加载访问令牌
            loadAcessToken(code)
            
        }else {
            print("取消授权")
            close()
        }
        return false
    }
    
    //MARK:- 使用授权码加载访问令牌
    private func loadAcessToken(code:String) {
        // 1.设置上传的参数
        let parameters = ["client_id":WB_Client_ID,"client_secret":WB_Client_Secret,"grant_type":WB_Grant_Type,"code":code,"redirect_uri":WB_Redirect_URI,]
        // 2.请求服务器
        NetWorkTools.sharedNetWorkTools.POST(WB_Token_UrlStr, parameters: parameters, success: { (_, JSON) -> Void in
            
            // 3.获取到json,字典转模型 并加载用户信息
            UserAccount(dict: JSON as! [String: AnyObject]).loadUserInfo() { (userAccount, error) in
                if userAccount != nil {
                    print(UserAccount)
                    sharedUserAccount = userAccount
                    
                    // 发送通知
                    // object = false 表示显示 WelcomeViewController
                    NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchMainInterfaceNotification, object: false)
                    
                    // 关闭当前控制器
                    self.close()
                    return
                }
                print(error)
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
            }
            
            }, failure: { (_, error) -> Void in
                print(error)
                SVProgressHUD.showInfoWithStatus("网络不给力")
        })

    }
    
    //MARK:- 开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showInfoWithStatus("正在加载...")
    }
    //MARK:- 完成加载
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    /// 点击关闭退出当前控制器
    func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true) { () -> Void in
            print("88")
        }
    }
    
    ///  懒加载webView
    lazy var lwebView: UIWebView = {
        return UIWebView()
    }()
    
}
